package kz.pdt12.hw.framework;

import kz.pdt12.hw.data.ContactData;
import kz.pdt12.hw.utils.SortedListOf;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * Created with IntelliJ IDEA.
 * User: raimbek
 * Date: 07.03.13
 * Time: 1:15
 */
public class ContactHelper extends WebDriverHelperBase {

    public static boolean CREATION = true;
    public static boolean MODIFICATION = false;

    public ContactHelper(ApplicationManager manager) {
        super(manager);
    }

    public ContactHelper createContact(ContactData contact) {
        manager.navigateTo().newContactPage();

        fillContactForm(contact, CREATION);
        submitContactCreation();
        gotoHomePage();
        manager.getModel().addContact(contact);
        return this;
    }

    public ContactHelper modifyContact(int index, ContactData contact) {
        manager.navigateTo().mainPage();

        editContactByIndex(index);
        // проверка то что поля открытого контакта соответсвует с базой данных
        checkContactWithDB();
        fillContactForm(contact, CREATION);
        updateContact();
        gotoHomePage();
        manager.getModel().removeContact(index).addContact(contact);
        return this;
    }

    private void checkContactWithDB() {
        ContactData contact = new ContactData();
        fillContactForm(contact, MODIFICATION);
        ContactData contactDb = manager.getHibernateHelper().getContact(contact.getId());
        assertThat(contact, equalTo(contactDb));
    }

    public ContactHelper deleteContact(int index) {
        manager.navigateTo().mainPage();

        editContactByIndex(index);
        deleteContact();
        gotoHomePage();
        manager.getModel().removeContact(index);
        return this;
    }

    public ContactHelper fillContactForm(ContactData contact, boolean formType) {
        By id = By.name("id");
        By firstname = By.name("firstname");
        By lastname = By.name("lastname");
        By address = By.name("address");
        By home = By.name("home");
        By mobile = By.name("mobile");
        By work = By.name("work");
        By email = By.name("email");
        By email2 = By.name("email2");
        By bday = By.name("bday");
        By bmonth = By.name("bmonth");
        By byear = By.name("byear");
        By group = By.name("new_group");
        By address2 = By.name("address2");
        By phone2 = By.name("phone2");

        type(firstname, contact.getFirstName());
        type(lastname, contact.getLastName());
        type(address, contact.getAddress());
        type(home, contact.getTelephoneHome());
        type(mobile, contact.getTelephoneMobile());
        type(work, contact.getTelephoneWork());
        type(email, contact.getEmail());
        type(email2, contact.getEmail2());
        selectByVisibleText(bday, contact.getBirthdayDay());
        selectByVisibleText(bmonth, contact.getBirthdayMonth());
        type(byear, contact.getBirthdayYear());
        if (formType == CREATION) {
            //selectByVisibleText(By.name("new_group"), contact.getGroup());
        } else {
            if (driver.findElements(group).size() != 0) {
                throw new Error("Group selector exists in contact modification form");
            }
        }
        type(address2, contact.getSecondaryAddress());
        type(phone2, contact.getSecondaryHomePhone());

        if (contact.getId() == null) {
            contact.setId(getTextElement(id));
        }

        if (contact.getFirstName() == null) {
            contact.setFirstName(getTextElement(firstname));
        }
        if (contact.getLastName() == null) {
            contact.setLastName(getTextElement(lastname));
        }
        if (contact.getAddress() == null) {
            contact.setAddress(getTextElement(address));
        }
        if (contact.getTelephoneHome() == null) {
            contact.setTelephoneHome(getTextElement(home));
        }
        if (contact.getTelephoneWork() == null) {
            contact.setTelephoneWork(getTextElement(work));
        }
        if (contact.getTelephoneMobile() == null) {
            contact.setTelephoneMobile(getTextElement(mobile));
        }
        if (contact.getEmail() == null) {
            contact.setEmail(getTextElement(email));
        }
        if (contact.getEmail2() == null) {
            contact.setEmail2(getTextElement(email2));
        }
        if (contact.getBirthdayDay() == null) {
            contact.setBirthdayDay(getSelectedValue(bday));
        }
        if (contact.getBirthdayMonth() == null) {
            contact.setBirthdayMonth(getSelectedValue(bmonth));
        }
        if (contact.getBirthdayYear() == null) {
            contact.setBirthdayYear(getTextElement(byear));
        }
        if (contact.getSecondaryAddress() == null) {
            contact.setSecondaryAddress(getTextElement(address2));
        }
        if (contact.getSecondaryHomePhone() == null) {
            contact.setSecondaryHomePhone(getTextElement(phone2));
        }
        return this;
    }

    public ContactHelper submitContactCreation() {
        driver.findElement(By.name("submit")).click();
        return this;
    }

    /**
     * Редактировать контакт по индексу
     * @param index
     * @return
     */
    public ContactHelper editContactByIndex(int index) {
        index++; // увеличиваем индекс, чтобы оставить заголовок таблицы
        index++; // увеличиваем еще раз, потому что в xpath индексация начинается с единицы
        click(By.xpath(".//tr[" + index + "]/.//td[7]/a/img[@src='icons/pencil.png']"));
        return this;
    }

    public ContactHelper deleteContact() {
        click(By.cssSelector("input[value='Delete']"));
        return this;
    }

    /**
     * Вернуться в главную страницу, после создания контакта
     */
    public void gotoHomePage() {
        driver.findElement(By.linkText("home page")).click();
    }

    public ContactHelper updateContact() {
        click(By.cssSelector("input[value='Update']"));
        return this;
    }

    public SortedListOf<ContactData> getUiContacts() {
        SortedListOf<ContactData> contacts = new SortedListOf<ContactData>();

        manager.navigateTo().mainPage();

        List<WebElement> elements = driver.findElements(
                By.xpath(".//table[@id='maintable']/tbody/tr[@class='odd' or @class='even']")
        );
        for (WebElement element : elements) {
            ContactData contact = new ContactData();
            contact.setLastName(element.findElement(By.xpath("td[2]")).getText());
            contact.setFirstName(element.findElement(By.xpath("td[3]")).getText());
            contact.setTelephoneHome(element.findElement(By.xpath("td[5]")).getText());

            contacts.add(contact);
        }
        return contacts;
    }
}
